import { ipcMain, BrowserWindow } from 'electron';
import { log, err as errlog } from '../utils/log';
import ApiServer from '../utils/http';
import Config, { Options } from '../utils/config';
import ServerStatus from '../utils/ServerStatus';


// 重置函数this指向
ipcMain.emit = ipcMain.emit.bind(ipcMain);


/**
 * 是否已经初始化
 */
const config = new Config();
let init = false;
let deConfig: Options;

const chatWindows = []//收集聊天窗口

export const onBrowserWindowCreated = (window: BrowserWindow) => {
  //监听preload发来的请求webContentsID
  window.webContents.on('ipc-message-sync', (event, channel) => {
    if (channel == '___!boot') {
      event.returnValue = {
        enabled: true,
        webContentsId: window.webContents.id.toString(),
      };
    }
  });

  window.webContents.on('did-stop-loading', async () => {
    if (window.id === 2 && chatWindows.length === 0) {//只改QQ主窗口就行了
      // @ts-expect-error: 该第三方库类型定义不完整，需要强制调用
      chatWindows.push(window)
    }
  })

  setTimeout(() => proxySend(window), 2000)
};

// 返回窗口id
ipcMain.on('LiteLoader.SDWebUI_ImageQuickSend.getWebContentId', (event) => {
  event.returnValue = event.sender.id.toString();
});

ipcMain.handle('LiteLoader.SDWebUI_ImageQuickSend.getConfig', () => config.getConfig())
ipcMain.on('LiteLoader.SDWebUI_ImageQuickSend.getOptions', (event) => {
  event.returnValue = config.getConfig();
});
ipcMain.on('LiteLoader.SDWebUI_ImageQuickSend.getServerStatus', (event) => {
  event.returnValue = ServerStatus.get();
});
ipcMain.handle('LiteLoader.SDWebUI_ImageQuickSend.setConfig', async (_event, newConfig) => config.setConfig(newConfig)) //更新配置，并且返回新的配置


/**
 * 主进程发消息通知所有渲染进程中的聊天窗口
 * @param message
 * @param args
 */
export function sendMsgToChatWindows(message, args) {
  for (const window of chatWindows) {
    // @ts-expect-error: 该第三方库类型定义不完整，需要强制调用

    if (window.isDestroyed()) continue;
    // @ts-expect-error: 该第三方库类型定义不完整，需要强制调用
    window.webContents.send(message, args);
  }
}


function proxySend(window) {
  // 复写并监听ipc通信内容
  const originalSend = window.webContents.send;
  window.webContents.send = async (...args) => {
    if (!init) {
      try {
        if (args?.[2]?.[0]?.cmdName === 'nodeIKernelSessionListener/onSessionInitComplete') {
          config.loadUserConfig(args?.[2]?.[0]?.payload?.uid);
          deConfig = config.getConfig();
          log(deConfig);
          onLoad();
          init = true;
        }
      } catch (err: any) {
        errlog('出现错误', err, err?.stack);
      }
    }
    originalSend.call(window.webContents, ...args);
  };
}


function onLoad() {
  const app = new ApiServer(deConfig);
  if (!deConfig.isActive) {
    log('服务未启动');
    ServerStatus.set('服务未启动');
    return;
  }
  app.start();
}
